package DAOs;

import DAOs.exceptions.NonexistentEntityException;
import Entity.Farm;
import Entity.ReforestationZone;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

/**
 *
 * @author USUARIO
 */
public class FarmJpaController implements Serializable {

    public FarmJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Farm farm) {
        if (farm.getReforestationZone() == null) {
            farm.setReforestationZone(new ArrayList<ReforestationZone>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            List<ReforestationZone> attachedReforestationZone = new ArrayList<ReforestationZone>();
            for (ReforestationZone reforestationZoneReforestationZoneToAttach : farm.getReforestationZone()) {
                reforestationZoneReforestationZoneToAttach = em.getReference(reforestationZoneReforestationZoneToAttach.getClass(), reforestationZoneReforestationZoneToAttach.getId());
                attachedReforestationZone.add(reforestationZoneReforestationZoneToAttach);
            }
            farm.setReforestationZone(attachedReforestationZone);
            em.persist(farm);
            for (ReforestationZone reforestationZoneReforestationZone : farm.getReforestationZone()) {
                Farm oldFarmOfReforestationZoneReforestationZone = reforestationZoneReforestationZone.getFarm();
                reforestationZoneReforestationZone.setFarm(farm);
                reforestationZoneReforestationZone = em.merge(reforestationZoneReforestationZone);
                if (oldFarmOfReforestationZoneReforestationZone != null) {
                    oldFarmOfReforestationZoneReforestationZone.getReforestationZone().remove(reforestationZoneReforestationZone);
                    oldFarmOfReforestationZoneReforestationZone = em.merge(oldFarmOfReforestationZoneReforestationZone);
                }
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Farm farm) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Farm persistentFarm = em.find(Farm.class, farm.getId());
            List<ReforestationZone> reforestationZoneOld = persistentFarm.getReforestationZone();
            List<ReforestationZone> reforestationZoneNew = farm.getReforestationZone();
            List<ReforestationZone> attachedReforestationZoneNew = new ArrayList<ReforestationZone>();
            for (ReforestationZone reforestationZoneNewReforestationZoneToAttach : reforestationZoneNew) {
                reforestationZoneNewReforestationZoneToAttach = em.getReference(reforestationZoneNewReforestationZoneToAttach.getClass(), reforestationZoneNewReforestationZoneToAttach.getId());
                attachedReforestationZoneNew.add(reforestationZoneNewReforestationZoneToAttach);
            }
            reforestationZoneNew = attachedReforestationZoneNew;
            farm.setReforestationZone(reforestationZoneNew);
            farm = em.merge(farm);
            for (ReforestationZone reforestationZoneOldReforestationZone : reforestationZoneOld) {
                if (!reforestationZoneNew.contains(reforestationZoneOldReforestationZone)) {
                    reforestationZoneOldReforestationZone.setFarm(null);
                    reforestationZoneOldReforestationZone = em.merge(reforestationZoneOldReforestationZone);
                }
            }
            for (ReforestationZone reforestationZoneNewReforestationZone : reforestationZoneNew) {
                if (!reforestationZoneOld.contains(reforestationZoneNewReforestationZone)) {
                    Farm oldFarmOfReforestationZoneNewReforestationZone = reforestationZoneNewReforestationZone.getFarm();
                    reforestationZoneNewReforestationZone.setFarm(farm);
                    reforestationZoneNewReforestationZone = em.merge(reforestationZoneNewReforestationZone);
                    if (oldFarmOfReforestationZoneNewReforestationZone != null && !oldFarmOfReforestationZoneNewReforestationZone.equals(farm)) {
                        oldFarmOfReforestationZoneNewReforestationZone.getReforestationZone().remove(reforestationZoneNewReforestationZone);
                        oldFarmOfReforestationZoneNewReforestationZone = em.merge(oldFarmOfReforestationZoneNewReforestationZone);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Long id = farm.getId();
                if (findFarm(id) == null) {
                    throw new NonexistentEntityException("The farm with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Long id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Farm farm;
            try {
                farm = em.getReference(Farm.class, id);
                farm.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The farm with id " + id + " no longer exists.", enfe);
            }
            List<ReforestationZone> reforestationZone = farm.getReforestationZone();
            for (ReforestationZone reforestationZoneReforestationZone : reforestationZone) {
                reforestationZoneReforestationZone.setFarm(null);
                reforestationZoneReforestationZone = em.merge(reforestationZoneReforestationZone);
            }
            em.remove(farm);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Farm> findFarmEntities() {
        return findFarmEntities(true, -1, -1);
    }

    public List<Farm> findFarmEntities(int maxResults, int firstResult) {
        return findFarmEntities(false, maxResults, firstResult);
    }

    private List<Farm> findFarmEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Farm.class));
            Query q = em.createQuery(cq);
            Query q1 = em.createNativeQuery("Select ID from farm");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
                q1.setMaxResults(maxResults);
                q1.setFirstResult(firstResult);
            }
            List<Farm> farmList = q.getResultList();
            for (int i = 0; i < farmList.size(); i++) {
                farmList.get(i).setId((Long) q1.getResultList().get(i));
            }
            return farmList;
        } finally {
            em.close();
        }
    }

    public Farm findFarm(Long id) {
        EntityManager em = getEntityManager();
        try {
            Farm farm = em.find(Farm.class, id);
            farm.setId(id);
            return farm;
        } finally {
            em.close();
        }
    }

    public int getFarmCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Farm> rt = cq.from(Farm.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
}
